package org.oy.sealogger.ui;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.util.Observable;
import java.util.Observer;

import org.oy.sealogger.parser.CurrentState;
import org.oy.sealogger.parser.RMCSentence;

public class Speed implements Observer {
	
	
	private String speedString = "0.0";
	
	private Image speed;
	private ImageLoader imageLoader = new ImageLoader();
	private LoggerGraphics lg = null;
	
	private int x;
	private int y;
	private int width;
	private int height;
	
	public Speed(LoggerGraphics l) {
		this.lg = l;
		speed = imageLoader.getImage("SPEED.png");	
	}

	
	//TODO: tekstin skaalaus ei toimi täydellisesti, 
	public void drawSpeedString(Graphics2D g2,int x, int y, int w, int h) {
    	int fontSize = (int)(Math.round(0.30 * w));
    	int yCenter = (int)(Math.round(0.25 * h));
    	int yString = y + (h / 2) + yCenter;
    	double speedDouble = Double.valueOf(speedString);
    	int xString = 0;
    	
    	if (speedDouble < 10.0) 
    		xString = (int)(Math.round(0.25 * w)) + x;
    	
    	if (speedDouble >= 10.0)
    		xString = (int)(Math.round(0.15 * w)) + x;
    	
        g2.setPaint(Color.BLACK);
		g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setFont(new Font("Arial", Font.BOLD, fontSize));
		g2.drawString(speedString,xString,yString);			
	}
	
	public void draw(Graphics g, int x, int y, int w, int h) {
		Graphics2D g2 = (Graphics2D)g;
		
		this.setVariables(x,y,w,h);	
		
		g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		g2.drawImage(speed, x, y, w, h, this.imageLoader);	
		
		this.drawSpeedString(g2,x,y,w,h);
	}
	
	private void setVariables(int x, int y, int w, int h) {
		this.x = x;
		this.y = y;
		this.width = w;
		this.height = h;
	}
	
	public void update(Observable state, Object arg) {
		RMCSentence rmc = ((CurrentState)state).getGPSLocation();
		this.setSpeed(rmc.getSpeed());
	}
	
	public void setSpeed(double speed) {
		speedString = Double.toString(speed);
		//this.lg.repaint(this.x,this.y,this.x + this.width,this.y + this.height);
		this.lg.repaint();
	}
	
}
